<template>
  <view class="container">
    <!-- 标题 -->
    <view class="header">
      <text class="title">我的收藏</text>
    </view>

    <!-- 收藏列表 -->
    <view class="song-list-vertical" v-if="favorites.length > 0">
      <view class="song-item-vertical" v-for="(song, index) in favorites" :key="song.song_id" @click="playSong(song, index)">
        <image class="song-cover-vertical" :src="song.cover_image_url" mode="aspectFill" />
        <view class="song-info-vertical">
          <text class="song-name-vertical">{{ song.name }}</text>
          <text class="song-artist-vertical">{{ song.artist_name }}</text>
        </view>
        <view class="song-actions">
          <text class="play-icon">▶️</text>
          <text class="remove-icon" @click.stop="removeFromFavorites(song.song_id)">🗑️</text>
        </view>
      </view>
    </view>

    <!-- 无收藏提示 -->
    <view class="empty-tip" v-else>
      <text class="empty-text">暂无收藏歌曲</text>
    </view>

    <!-- 底部播放器 -->
    <view class="mini-player" v-if="currentSong" @click="goToPlayer">
      <image class="mini-player-cover" :src="currentSong.cover_image_url" mode="aspectFill" />
      <view class="mini-player-info">
        <text class="mini-player-name">{{ currentSong.name }}</text>
        <text class="mini-player-artist">{{ currentSong.artist_name }}</text>
      </view>
      <view class="mini-player-controls">
        <text class="control-btn" @click.stop="togglePlay">
          {{ isPlaying ? '⏸️' : '▶️' }}
        </text>
        <text class="control-btn" @click.stop="nextSong">⏭️</text>
      </view>
    </view>
  </view>
</template>

<script>
// 内联API配置以避免模块导入问题
const BASE_URL = 'http://localhost:3000/api'

function request(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }

    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 导入音乐播放器
import musicPlayer from '/utils/musicPlayer.js'

const api = {
  music: {
    getFavorites() {
      return request({
        url: '/music/favorites',
        method: 'GET'
      })
    },
    
    // 添加收藏
    addFavorite(songId) {
      return request({
        url: '/music/favorite',
        method: 'POST',
        data: { songId }
      })
    },
    
    // 取消收藏
    removeFavorite(songId) {
      return request({
        url: `/music/favorite/${songId}`,
        method: 'DELETE'
      })
    },
    
    // 获取歌曲详情
    getSongDetail(songId) {
      return request({
        url: `/music/song/${songId}`,
        method: 'GET'
      })
    }
  }
}

export default {
  data() {
    return {
      favorites: [],
      currentSong: null,
      isPlaying: false
    }
  },

  onShow() {
    this.loadFavorites()
  },

  methods: {
    // 加载收藏列表
    async loadFavorites() {
      try {
        const response = await api.music.getFavorites()
        this.favorites = response.data || []
      } catch (error) {
        console.error('加载收藏列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 播放歌曲
    async playSong(song, index) {
      // 获取歌曲详情（这会自动记录播放历史）
      try {
        const response = await api.music.getSongDetail(song.song_id)
        const songDetail = response.data || song
        
        // 设置播放列表（使用收藏列表）
        musicPlayer.setPlaylist(this.favorites, index)
        
        // 更新当前歌曲状态
        this.currentSong = songDetail
        this.isPlaying = true
      } catch (error) {
        console.error('获取歌曲详情失败:', error)
        uni.showToast({
          title: '播放失败',
          icon: 'none'
        })
      }
    },

    // 切换播放状态
    togglePlay() {
      musicPlayer.togglePlay()
      this.isPlaying = musicPlayer.getCurrentInfo().isPlaying
    },

    // 下一首
    nextSong() {
      musicPlayer.next()
      const playerInfo = musicPlayer.getCurrentInfo()
      this.currentSong = playerInfo.song
      this.isPlaying = playerInfo.isPlaying
    },

    // 跳转到播放器页面
    goToPlayer() {
      uni.navigateTo({
        url: '/pages/player/player'
      })
    },
    
    // 从收藏中移除
    async removeFromFavorites(songId) {
      try {
        const response = await api.music.removeFavorite(songId)
        if (response.code === 200) {
          // 从本地列表中移除
          this.favorites = this.favorites.filter(song => song.song_id !== songId)
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
        } else {
          throw new Error(response.message || '取消收藏失败')
        }
      } catch (error) {
        console.error('取消收藏失败:', error)
        uni.showToast({
          title: '取消收藏失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header {
  padding: 30rpx;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.song-list-vertical {
  display: flex;
  flex-direction: column;
}

.song-item-vertical {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.song-cover-vertical {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.song-info-vertical {
  flex: 1;
}

.song-name-vertical {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-artist-vertical {
  display: block;
  font-size: 24rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.play-icon, .remove-icon {
  font-size: 30rpx;
  padding: 10rpx;
  margin: 5rpx 0;
}

.play-icon {
  color: #ff6b6b;
}

.remove-icon {
  color: #999;
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.mini-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.mini-player-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.mini-player-info {
  flex: 1;
}

.mini-player-name {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 5rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-artist {
  display: block;
  font-size: 22rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-controls {
  display: flex;
  align-items: center;
}

.control-btn {
  font-size: 40rpx;
  margin-left: 20rpx;
  padding: 10rpx;
}
</style>